(function() {
  'use strict';

  angular

    .module('cf-content')

  .run(appRun);

  appRun.$inject = ['$rootScope', '$state', '$stateParams','$timeout', '$cookieStore', 'Api', 'AUTH_EVENTS', 'USER_ROLES'];

  function appRun($rootScope, $state, $stateParams,$timeout, $cookieStore, Api, AUTH_EVENTS, USER_ROLES) {

    $timeout(function(){
      if(!$state.current.auth){
        Api.Logintype.Check().$promise.then()
      }
    },500,true)

    $rootScope.$on('$stateChangeStart', function(event, toState) {
      if (!toState.auth)
        Api.Logintype.Check().$promise.then(function(data) {
        if (data.code == 401) {
          // user not login in
          $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);

          $cookieStore.remove('CFTOKEN')

        } else if (data.data.type != USER_ROLES.ADMIN) {

          $cookieStore.remove('CFTOKEN')

          // user is not allowed
          $rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
        }

      })
    });

    $rootScope.$on(AUTH_EVENTS.notAuthenticated, function(data) {
      $state.go('login')
    })

    $rootScope.$on(AUTH_EVENTS.notAuthorized, function(data) {
      $state.go('login')
    })

  }

})();